<?php
declare(strict_types=1);

namespace app\model;

use think\Model;

class ExpressPriceCache extends Model
{
    protected $name = 'express_price_cache';
    
    protected $autoWriteTimestamp = true;
    
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    /**
     * 获取价格缓存
     */
    public static function getPriceCache(
        int $providerId,
        string $fromProvince,
        string $fromCity,
        string $toProvince,
        string $toCity
    ): ?self {
        return self::where([
            'express_service_provider_id' => $providerId,
            'from_province' => $fromProvince,
            'from_city' => $fromCity,
            'to_province' => $toProvince,
            'to_city' => $toCity
        ])->find();
    }

    /**
     * 更新价格缓存
     */
    public static function updatePriceCache(
        int $providerId,
        string $fromProvince,
        string $fromCity,
        string $toProvince,
        string $toCity,
        float $firstPrice,
        float $continuedPrice
    ): bool {
        $cache = self::getPriceCache($providerId, $fromProvince, $fromCity, $toProvince, $toCity);
        
        if ($cache) {
            return $cache->save([
                'first_price' => $firstPrice,
                'continued_price' => $continuedPrice
            ]);
        }

        return self::create([
            'express_service_provider_id' => $providerId,
            'from_province' => $fromProvince,
            'from_city' => $fromCity,
            'to_province' => $toProvince,
            'to_city' => $toCity,
            'first_price' => $firstPrice,
            'continued_price' => $continuedPrice
        ]) ? true : false;
    }

    /**
     * 清理过期缓存
     */
    public static function clearExpired(int $days = 7): bool
    {
        return self::where('create_time', '<', date('Y-m-d H:i:s', strtotime("-{$days} days")))
            ->delete();
    }
} 